use actix_web::web::{Json};
use actix_web::{post, web::Data};
use deadpool_redis::Pool as RedisPool;
use crate::business::entity::user::User;
use crate::extends::core::cached::redis_util::RedisUtil;
use crate::extends::core::response::reponse_data::*;
use crate::extends::utils::md5_util::Md5Util;

const REDIS_KEY_PREFIX: &str = "user";

#[post("/admin/cache/user/save")]
pub async fn save(pool: Data<RedisPool>, user: Json<User>) -> Json<R<String>> {
    let user_id = user.id.expect("User ID is required");
    let key = format!("{}::{}", REDIS_KEY_PREFIX, Md5Util::compute_md5(&user_id.to_string()));

    // 使用解包后的 user 以获得 &User 类型
    RedisUtil::new_by_ctx_pool(pool).set_struct(&key, &*user).await.expect("Failed to set key in Redis");

    R::success(Some(format!("User with id {} saved successfully.", user_id)))
}

#[post("/admin/cache/user/update")]
pub async fn update(pool: Data<RedisPool>, user: Json<User>) -> Json<R<String>> {
    let user_id = user.id.expect("User ID is required");
    let key = format!("{}::{}", REDIS_KEY_PREFIX, Md5Util::compute_md5(&user_id.to_string()));

    // 使用解包后的 user 以获得 &User 类型
    RedisUtil::new_by_ctx_pool(pool).set_struct(&key, &*user).await.expect("Failed to update key in Redis");

    R::success(Some(format!("User with id {} updated successfully.", user_id)))
}

#[post("/admin/cache/user/delete")]
pub async fn delete(pool: Data<RedisPool>, user: Json<User>) -> Json<R<String>> {
    let user_id = user.id.expect("User ID is required");
    let key = format!("{}::{}", REDIS_KEY_PREFIX, Md5Util::compute_md5(&user_id.to_string()));

    RedisUtil::new_by_ctx_pool(pool).delete(&key).await.expect("Failed to delete key from Redis");

    R::success(Some(format!("User with id {} deleted successfully.", user_id)))
}
#[post("/admin/cache/user/find")]
pub async fn find(pool: Data<RedisPool>, user: Json<User>) -> Json<R<User>> {
    let user_id = user.id.expect("User ID is required");
    let key = format!("{}::{}", REDIS_KEY_PREFIX, Md5Util::compute_md5(&user_id.to_string()));

    let result: Option<User> = RedisUtil::new_by_ctx_pool(pool).get_struct(&key).await.expect("Failed to get key from Redis");

    R::success(result)
}